/**
 * Created by zy on 2016/6/13.
 * 变化趋势/数据对比分析(共用) - 管体缺陷仪表板 - 管体缺陷
 */


;(function ($, window, document, undefined) {

    /*** 管道联动操作 - start ***/
    // 管道
    var $pipeline = $('#JQ_pipeline').select3();
    // 管段
    var $segment = $('#JQ_segment').select3({
        title: '管段'
    });
    // 起点位置
    var $begin = $('#JQ_begin').select3({
        title: '起点位置',
        server: true,
        mileType: 'float',
        param: {
            'pipeLineId': $pipeline,
            'pipeSegmentId': $segment
        }
    });
    // 终点位置
    var $end = $('#JQ_end').select3({
        title: '终点位置',
        server: true,
        mileType: 'float',
        param: {
            'pipeLineId': $pipeline,
            'pipeSegmentId': $segment,
            'beginSignId': $begin
        }
    });
    // 检测任务 - 01
    var $task_01 = $('#JQ_task_01').select3({
        search: false
    });
    // 检测任务 - 02
    var $task_02 = $('#JQ_task_02').select3({
        search: false
    });

    // 填充管段
    function fillSegment(id) {
        if (id) {
            DyyBase.ajax(DyyBase.url_segment(), {pipeLineId: id}, function (dataset) {
                var json = DyyBase.getSelect(dataset);
                $segment.add(json);
            }, {async: false});
        } else {
            $segment.add([]);
        }
    }

    // 填充起点&终点
    function fillPos(id, tag) {
        if (id) {
            if (tag === 'pipe') {
                DyyBase.ajax(DyyBase.url_pipe_pos(), {pipeLineId: id}, function (dataset) {
                    var begin = DyyBase.getPos(dataset, 'begin', true);
                    var end = DyyBase.getPos(dataset, 'end', true);
                    $begin.asset(begin);
                    $end.asset(end);
                }, {async: false});
            } else if (tag === 'segment') {
                DyyBase.ajax(DyyBase.url_segment_pos(), {pipeSegmentId: id}, function (dataset) {
                    var begin = DyyBase.getPos(dataset, 'begin', true);
                    var end = DyyBase.getPos(dataset, 'end', true);
                    $begin.asset(begin);
                    $end.asset(end);
                }, {async: false});
            }
        } else {
            $begin.add([]);
            $end.add([]);
        }
    }

    // 填充检测任务
    function fillTask(id) {
        if ($task_01.length && $task_02.length) {
            if (id) {
                DyyBase.ajax(defectApi.url_board_task(), {lineId: id}, function (dataset) {
                    var json = DyyBase.getSelect(dataset);
                    $task_01.asset(json);
                    $task_02.asset(json);
                }, {async: false});

                // 相异
                setDifference();
            } else {
                $task_01.add([]);
                $task_02.add([]);
            }
        }
    }

    // 触发管道
    $pipeline.element.on('select', function (e, v) {
        var id = v || $pipeline.val();
        fillSegment(id);
        fillPos(id, 'pipe');
        fillTask(id);
    });
    // 触发管段
    $segment.element.on('select', function (e, v) {
        var id = v || $segment.val();
        fillPos(id, 'segment');
    });

    // 默认触发第一条管道
    $pipeline.element.trigger('select');
    /*** 管道联动操作 - end ***/


    // 将检测任务置为相异
    function setDifference() {
        if ($task_02.length > 0) {
            var store = $task_02.val('store');
            if (store.length > 1) {
                var id2 = store[1]['id'];
                $task_02.fit(id2);
            }
        }
    }

    // 初始趋势表
    var $trend_table = $('#JQ_trend_table_01');
    var trend_table_clone = $trend_table.html();
    // 初始趋势图表
    var $trend_charts = $('#JQ_trend_charts');
    var trend_charts_clone = $trend_charts.html();


    // 搜索条件
    var filter = {
        getCondition: function () {
            var data = {};
            data.mode = true;
            // 管道ID
            data.lineId = function () {
                var v = $pipeline.val();
                if (v) {
                    return v;
                } else {
                    $pipeline.element.TIP({content: '管道名称不能为空!'});
                    data.mode = false;
                }
                return '';
            }();
            // 管段ID
            data.inspSegmentId = function () {
                var v = $segment.val();
                if (v) {
                    return v;
                }
                return '';
            }();
            // 起点位置
            data.beginMileage = function () {
                if ($task_01.length === 0) {
                    return $begin.val('mile');
                } else {
                    return '';
                }
            }();
            // 终点位置
            data.endMileage = function () {
                if ($task_02.length === 0) {
                    return $end.val('mile');
                } else {
                    return '';
                }
            }();
            // 检测任务 - 01
            data.taskId1 = function () {
                if ($task_01.length > 0) {
                    var v = $task_01.val();
                    if (v) {
                        return v;
                    } else {
                        $task_01.element.TIP({content: '数据对比内容不能为空!'});
                        data.mode = false;
                    }
                    return '';
                }
                return '';
            }();
            // 检测任务 - 02
            data.taskId2 = function () {
                if ($task_02.length > 0) {
                    var v = $task_02.val();
                    if (v) {
                        return v;
                    } else {
                        $task_02.element.TIP({content: '数据对比内容不能为空!'});
                        data.mode = false;
                    }
                    return '';
                }
                return '';
            }();
            // 检测任务是否相同
            data.taskSame = function () {
                var v1 = $task_01.length > 0 ? $task_01.val() : '';
                var v2 = $task_02.length > 0 ? $task_02.val() : '';
                if (v1 && v2 && v1 === v2) {
                    $task_02.element.TIP({content: '两次检测任务不能相同!'});
                    data.mode = false;
                }
            }();
            // 转化
            return data;
        }
    };

    // 查询
    $('#JQ_search_btn_01').click(function () {
        var $this = $(this);
        var param = filter.getCondition();
        var url = defectApi.url_board_trend();
        if ($this.hasClass('analysis')) {
            url = defectApi.url_board_analysis();
        }
        if (param.mode) {
            DyyBase.ajax(url, param, function (dataset) {
                if(dataset.bool){
                    if(dataset.message == 'false'){
                        $trend_table.empty().html(trend_table_clone);
                        $trend_charts.empty().html(trend_charts_clone);
                        DyyBase.setChartWidth();
                        $this.MSG({
                            type: 'error',
                            content: dataset.result
                        });
                    }else{
                        var result = dataFormat.getChangeTrendTable(dataset);
                        if (result.length > 0) {
                            $trend_table.empty().html(result);
                            // 查询成功为导出添加成功状态
                            $('#JQ_export_btn_01').attr('data-status', 'true');
                        }
                        // 生成图表
                        dataFormat.drawCharts(dataset.result);
                    }
                }else{
                    $this.MSG({
                        type: 'error',
                        content: dataset.result
                    });
                }
            });
        }
    });

    // 数据格式化
    var dataFormat = {
        // 获得缺陷变化趋势数据
        getChangeTrendTable: function (data) {

            /*data = {
                result: {
                    one: [
                        {NUM: 10, TYPE: '内部金属损失'},
                        {NUM: 0, TYPE: '外部金属损失'},
                        {NUM: 0, TYPE: '凹陷'},
                        {NUM: 0, TYPE: '环焊缝异常'},
                        {NUM: 0, TYPE: '螺旋焊缝异常'}
                    ],
                    two: [
                        {NUM: 5, TYPE: '内部金属损失'},
                        {NUM: 7, TYPE: '外部金属损失'},
                        {NUM: 2, TYPE: '凹陷'},
                        {NUM: 3, TYPE: '环焊缝异常'},
                        {NUM: 1, TYPE: '螺旋焊缝异常'}
                    ],
                    oneDate: '2016.08.01',
                    twoDate: '2016.08.07'
                }
            };*/
            // 检测时间 1-2
            var date_01 = data.result.oneDate,
                date_02 = data.result.twoDate;
            date_01 = date_01.split('.'), date_02 = date_02.split('.');
            date_01 = date_01[0] + '年' + date_01[1] + '月' + date_01[2] + '日';
            date_02 = date_02[0] + '年' + date_02[1] + '月' + date_02[2] + '日';
            $('#JQ_test_date_01').text(date_01);
            $('#JQ_test_date_02').text(date_02);


            // 日期 1 - 2
            var num_1 = [], num_2 = [];
            var percent = [], name = [], number = [], result = [];
            for (var i = 0, len = data.result.one.length; i < len; i++) {
                name.push(data.result.one[i].TYPE);
                var one = parseInt(data.result.one[i].NUM); num_1.push(one);
                var two = parseInt(data.result.two[i].NUM); num_2.push(two);
                var num = two - one;
                var temp = '-';
                if (one !== 0) {
                    temp = ((num / one) * 100.00).toFixed(2);
                }
                number.push(num);
                percent.push(temp);
            }
            for (var j = 0, lens = name.length; j < lens; j++) {
                var obj = {};
                obj.name = name[j];
                obj.num_1 = num_1[j];
                obj.num_2 = num_2[j];
                obj.number = number[j];
                obj.percent = percent[j] === '-' ? percent[j] : percent[j] + '%';
                result.push(obj);
            }
            var p = '';
            for (var idx in result) {
                p += '<p>'
                    + '<span style="width: 20%">' + result[idx].name + '</span>'
                    + '<span style="width: 20%">' + result[idx].num_1 + '</span>'
                    + '<span style="width: 20%">' + result[idx].num_2 + '</span>'
                    + '<span style="width: 20%">' + result[idx].number + '</span>'
                    + '<span style="width: 20%">' + result[idx].percent + '</span>'
                    + '</p>'
            }
            return p;
        },
        // 生成图表1
        drawCharts: function (dataset) {
            //console.log(dataset);
            try {
                window.drawCharts(dataset);
            } catch (e) {
                alert(e);
            }
        },
        // 查询数据
        queryData: function (start, end) {
            $('div.zy-charts-float-msg').hide();
            var param = filter.getCondition();
            delete(param['beginMileage']);
            delete(param['endMileage']);
            param.beginMileage = start;
            param.endMileage = end;
            DyyBase.ajax(defectApi.url_board_trend(), param, function (dataset) {
                try {
                    drawChartsOnssse(dataset);
                } catch (e) {
                    throw new Error(e);
                }
            });
        }
    };

    window.dataFormat = dataFormat;

    // 切换
    $trend_charts.on('click','li',function(){
        var $this_li = $(this);
        $this_li.siblings('li').removeClass('active');
        $this_li.addClass('active');

        var $tabs = $('div.zy-charts-bodys').find('div.zy-charts-body');
        var $divs = $('#JQ_text_info').find('div');
        $tabs.hide().eq($this_li.index()).show();
        $divs.hide().eq($this_li.index()).show();
        $('div.zy-charts-float-msg').hide();

        $(".zy-defect-text ").hide();
        $(".zy-defect-text ").eq($(".zy-charts-tabs li.active").index()).show();
    });

})(jQuery, window, document);